package client.Protocal;

import com.alibaba.fastjson.JSON;
import common.EnvelopeMessage;

import java.io.*;
import java.net.Socket;


public class ClientSocket {
    private Socket socket;
    private BufferedWriter writer;
    private MessageListener listener;

    private Thread heartbeatThread;
    private boolean running = true;

    public ClientSocket(String host, int port) {
        try {
            socket = new Socket(host, port);
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            new Thread(this::listen).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setMessageListener(MessageListener listener) {
        this.listener = listener;
    }

    public void send(EnvelopeMessage msg) {
        try {
            String json = JSON.toJSONString(msg);
            writer.write(json);
            writer.newLine();
            writer.flush();
            System.out.println("客户端发送：" + json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void listen() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null&&running) {
                System.out.println("收到服务端消息：" + line);
                EnvelopeMessage msg = JSON.parseObject(line, EnvelopeMessage.class);
                if (listener != null) {
                    listener.onMessage(msg);
                }
            }
            System.out.println("服务端断开连接，或客户端主动关闭，结束！！！");
            close();
        } catch (IOException e) {
            e.printStackTrace();
            close();
        }
    }
    public void startHeartbeat() {
        heartbeatThread = new Thread(() -> {
            while (running) {
                try {
                    EnvelopeMessage heartbeat = new EnvelopeMessage("heart", "beat", null);
                    send(heartbeat);
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    break;
                }
            }
        });
        heartbeatThread.setDaemon(true);//守护线程，不会阻止程序退出

        heartbeatThread.start();
    }
    public void close() {
        running = false;
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}



